package generics;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import persistence.JPAUtil;

public abstract class ImpGenericDAO<T, PK extends Serializable> implements InterfaceGenericDAO<T, PK> {

	EntityManager em = JPAUtil.getEntityManager();
	
	@Override
	public T save(T entity) {
		
		T saved = null;
		
		em.getTransaction().begin();
		saved = em.merge(entity);
		em.getTransaction().commit();
		
		return saved;
	}

	@Override
	public void remove(T entity) {
		em.getTransaction().begin();
		em.remove(entity);
		em.getTransaction().commit();
	}

	@Override
	public T getById(Class<T> classe, PK pk) {
		try {
			return em.find(classe, pk);
		} catch (NoResultException e) {
			return null;
		}
	}

	@Override
	public List<T> getAll(Class<T> classe) {
		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT e FROM ");
		sql.append(classe.getSimpleName());
		sql.append(" e");
		return em.createQuery(sql.toString()).getResultList();
	}
	
}
